﻿package bdz.controls
{
	
	import bdz.common.events.GenericEvent;
	
	import com.senocular.display.*;
	
	import flash.display.*;
	import flash.events.*;
	import flash.geom.Matrix;
	import flash.utils.setTimeout;
	
	import mx.core.UIComponent;
	/**
	 * ...
	 * @author ...
	 */
	public class ControlElement extends EventDispatcher 
	{
		
		private var _element:DisplayObject;
		private var _modifier:TransformTool;
		private var _stage:Stage;
		private var _enabled:Boolean = true;
		private var _defSettings:Object;
		private var _manMatrix:Function;
		function ControlElement(targ:DisplayObject, stg:Stage, def:Object = null, manualMatrix:Function = null):void {
			_element = targ;
			_stage = stg;
			_defSettings = def;
			_manMatrix = manualMatrix;
			//targ.addEventListener(Event.ADDED_TO_STAGE, initialize);
			setTimeout(initialize, 50);
		}
		private function initialize(evt:Event = null):void {
			
			_modifier = new TransformTool();
			if(_defSettings){
				for(var prop:String in _defSettings){
					_modifier[prop] = _defSettings[prop];
				}	
			}else{
				_modifier.constrainScale = true;
				_modifier.moveEnabled = true;
			}
			if(_manMatrix != null){
				_modifier.addEventListener(GenericEvent.CHANGE, _manMatrix);
			}
			_element.addEventListener(MouseEvent.MOUSE_OVER, onMouseAction);
			try{
				_element.parent.addChild(_modifier);
			}catch(e:Error){
				try{
					var ui:UIComponent = new UIComponent();
					ui.addChild(_modifier);
					_element.parent.addChild(ui);
				}catch(e:Error){
					
				}
			}
			
			_modifier.stage.addEventListener(MouseEvent.MOUSE_UP, onMouseAction);
		}
		private function onStageMouse(evt:MouseEvent):void {
			_modifier.target = null;	
		}
		
		private function onMouseAction(evt:MouseEvent):void {
			if(evt.type == MouseEvent.MOUSE_OVER){
				_modifier.target = _element;
			}else {
				_modifier.target = null;
			}
			
		}
		public function set newTarget(targ:DisplayObject):void {
			_element = targ;
			try {
				_modifier.target = _element
			}catch (e:Error) {
				
			}
		}
		public function set enabled(e:Boolean):void {
			try{
				_enabled = e;
				_modifier.stage.removeEventListener(MouseEvent.MOUSE_UP, onMouseAction);
				_element.removeEventListener(MouseEvent.MOUSE_OVER, onMouseAction);
				if (e) {
					_modifier.stage.addEventListener(MouseEvent.MOUSE_UP, onMouseAction);
					_element.addEventListener(MouseEvent.MOUSE_OVER, onMouseAction);
				}
			}catch (e:Error) {
				
			}
		}
		public function set visible(b:Boolean):void {
			try{
				_modifier.visible = b;
			}catch (e:Error) {
				
			}
		}
		public function get enabled():Boolean {
			return _enabled;
		}
		public function get transformMatrix():Matrix {
			return _modifier.transformMatrix;
		}
		
	}
	
}